package com.ls.fw.biz.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.ls.fw.biz.form.IndexForm;
import com.ls.fw.commons.config.property.FwPropertyPlaceholderConfigurer;
import com.ls.fw.commons.log.exception.ExceptionsHelper;
import com.ls.fw.data.bean.ResultStatus;
import com.ls.fw.data.bean.ResultTemplate;
import com.ls.fw.data.exception.DataException;
import com.ls.fw.mvc.springmvc.base.BaseCRUDController;
import com.ls.fw.mvc.springmvc.util.ViewUtil;
import com.ls.fw.sdk.open.OpenClient;

@Controller
public class IndexController extends BaseCRUDController {
	static String appId = "admin";
	static String secret = "123456";

	@Resource
	private FwPropertyPlaceholderConfigurer propertyConfigurer;
	static OpenClient client = new OpenClient(appId, secret);
	boolean stop = true;
    ExecutorService executor = Executors.newCachedThreadPool();
	@RequestMapping("/")
    public ModelAndView log(HttpServletRequest req) {
        ModelAndView mavAndView = new ModelAndView("/index");
        mavAndView.addObject("status", stop);
		return mavAndView;
    }  
	
	@RequestMapping("/stop")
    public ModelAndView stop(WebRequest webRequest,HttpServletRequest req) throws Exception {
    	String method = Thread.currentThread() .getStackTrace()[1].getMethodName();
    	String mapping = this.methodRequestMapping.get(method);
    	return ViewUtil.convert(this.doSave(null, webRequest, this.viewPrefix+mapping
                , new SaveWorkHandler<String>() {

   			@Override
   			public ResultTemplate doWork(String body, WebRequest webRequest)
   					throws Exception {
   				ResultTemplate obj = ResultTemplate.newInstance();
   				ResultStatus status = ResultStatus.BAD_REQUEST;
   				try {
   					stop = true;
   					status = (ResultStatus.OK);
   				} catch (JSONException e) {
   					logger.error(e.getMessage(), e);
   					obj.setMsg("提交的数据为非法json格式！");
   				} catch (DataException e) {
   					logger.error(e.getMessage(), e);
//   					status = ResultStatus.valueOf(e.getStatus());
   					obj.setMsg(e.getMessage());
   				} catch (Exception e) {
   					logger.error(e.getMessage(), e);
   					obj.setMsg(ExceptionsHelper.getRootCause(e).getMessage());
   				} finally{
   					obj.setStatus(status);
   				}
   				return obj;
   			}
   		}), webRequest,true);
	}
    
	@RequestMapping("/start")
    public ModelAndView start(WebRequest webRequest,HttpServletRequest req,IndexForm form) throws Exception {
    	String method = Thread.currentThread() .getStackTrace()[1].getMethodName();
    	String mapping = this.methodRequestMapping.get(method);
    	return ViewUtil.convert(this.doSave(null, webRequest, this.viewPrefix+mapping
                , new SaveWorkHandler<String>() {

   			@Override
   			public ResultTemplate doWork(String body, WebRequest webRequest)
   					throws Exception {
   				ResultTemplate obj = ResultTemplate.newInstance();
   				ResultStatus status = ResultStatus.BAD_REQUEST;
   				try {
   					if(!stop){
   						throw new Exception("正在导入模拟数据，不能开始导入，请导入完毕后，再执行导入！");
   					}
   					stop = false;
   					final int max = form.getCount();
   					final int step = 1000;
   					String url= propertyConfigurer.getPropsMap().get("api.url");
   					Future<Boolean> f = executor.submit(new Callable<Boolean>() { 
						@Override
						public Boolean call() throws Exception{
							int add = 0;
		   					int index = 0;
		   					Map<String,String> map = new HashMap<String, String>();
	   						map.put("schema", form.getSchema());
	   						map.put("table", form.getTable());
	   						map.put("appKey", appId);
	   						map.put("timestrap", new Date().getTime()+"");
		   					while(!stop){
		   						int more = (max-add);
			   					int onceCount = more>step?step:more;
			   					add += onceCount;
			   					List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		   						while(onceCount>0){
			   						Map<String,String> map1 = new HashMap<String, String>();
			   						map1.put("name", "name"+(index++));
			   						list.add(map1);
			   						onceCount--;
		   						}
		   						String  resp = "";
		   						try {
									resp = client.post(url, map,JSON.toJSONString(list));
									ResultTemplate t =   JSON.parseObject(resp, ResultTemplate.class);
									if(t.getStatus()!=200){
										stop = true;
										System.out.println(t.getMsg());
									}
		   						} catch (Exception e) {
									e.printStackTrace();
									stop = true;
								}
		   						System.out.println("添加了："+index);
		   						if(add>=max){
		   							stop = true;
		   						}
		   					}
		   					return stop;
						}
					});
   					status = (ResultStatus.OK);
   				} catch (JSONException e) {
   					logger.error(e.getMessage(), e);
   					obj.setMsg("提交的数据为非法json格式！");
   					stop = true;
   				} catch (DataException e) {
   					stop = true;
   					logger.error(e.getMessage(), e);
//   					status = ResultStatus.valueOf(e.getStatus());
   					obj.setMsg(e.getMessage());
   				} catch (Exception e) {
   					stop = true;
   					logger.error(e.getMessage(), e);
   					obj.setMsg(ExceptionsHelper.getRootCause(e).getMessage());
   				} finally{
   					obj.setStatus(status);
   				}
   				return obj;
   			}
   		}), webRequest,true);
	}
    
}
